import {PlusOutlined} from '@ant-design/icons';
import {Button, Divider, message, Input, Drawer, DatePicker, Select, Form, Modal, Tree} from 'antd';
import {ExclamationCircleOutlined} from '@ant-design/icons';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import RoleForm from './components/RoleForm';
import {
  queryRole,
  updateRole,
  addRole,
  removeRole,
  queryAccount,
  queryAllMenu,
  queryRoleMenus
} from '@/services/system';


const initRecord = {
  roleName: '',
  roleCode: '',
  menuIds: [],
  remark: ''
}


const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState(['0-0-0', '0-0-1']);
  const [checkedKeys, setCheckedKeys] = useState(['0-0-0']);
  const [realCheckedKeys, setRealCheckedKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [roleMenus, setRoleMenus] = useState([]);
  const [formTitle, setFormTitle] = useState('新增角色');
  const [menuTree, setMenuTree] = useState([]);
  const actionRef = useRef();
  const [formRef] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRecord, setSelectedRecord] = useState({});
  const {Option} = Select;
  const {RangePicker} = DatePicker;


  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');

    try {
      await addRole({...fields, menuIds: realCheckedKeys}).then(res => {
        hide();
        if (res.status === '0') {
          message.success('添加成功');
        } else {
          message.error(res.message);
        }
      });
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  const handleUpdate = async (fields) => {
    fields.roleId = selectedRecord.roleId
    const hide = message.loading('正在配置');

    try {
      await updateRole({
        ...fields,
        menuIds: realCheckedKeys
      }).then(res => {
        hide();
        if (res.status === '0') {
          message.success('配置成功');
        } else {
          message.error(res.message);
        }
      });
      return true;
    } catch (error) {
      hide();
      message.error('配置失败请重试！');
      return false;
    }
  };

  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      await removeRole({
        ...selectedRows
      }).then(res => {
        hide();
        if (res.status === '0') {
          message.success('删除成功，即将刷新');
        } else {
          message.error(res.message);
        }
      });
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }

    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  const renderMenuTree = (menuList) => {
    const menuTreeData = menuList.filter(item => {
      if (item.menuType === 1 && !item.menuPid) {
        item.key = item.menuId
        item.title = item.menuName
        item.children = [];
      }
      return item.menuType === 1 && !item.menuPid
    })
    menuList.filter(item => item.menuType === 1 && item.menuPid).forEach(item => {
      menuTreeData.forEach(parent => {
        if (parent.menuId === item.menuPid) {
          item.key = item.menuId
          item.title = item.menuName
          parent.children.push(item);
        }
      })
    })
    setMenuTree(menuTreeData)
  }
  useEffect(() => {
    queryAllMenu().then(res => {
      if (res && res.status === '0') {
        const menuList = res.data;
        renderMenuTree(menuList)
      }
    })
  }, [])

  const handleUpdateModalVisible = (record) => {
    setSelectedRecord(record)
    formRef.setFieldsValue({
      ...record
    })
    setFormTitle('更新角色')
    handleModalVisible(true)
    getRoleMenus(record)
  }
  const handleCreateModalVisible = () => {
    formRef.setFieldsValue({
      ...initRecord
    })
    setFormTitle('新增角色')
    handleModalVisible(true)
  }

  const onExpand = (expandedKeysValue) => {
    //console.log(('onExpand', expandedKeysValue);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue, info) => {
    //console.log(('onCheck', checkedKeysValue);
    setCheckedKeys([...checkedKeysValue]);
    setRealCheckedKeys([...checkedKeysValue, ...info.halfCheckedKeys]);
  };

  const onSelect = (selectedKeysValue, info) => {
    //console.log(('onSelect', info);
    setSelectedKeys(selectedKeysValue);
  };

  const deleteConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `是否要删除名称为 【${record.roleName} 】的角色？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        handleRemove(record)
      }
    });
  };

  const getRoleMenus = (role) => {
    queryRoleMenus(role).then(res => {
      if (res && res.status === '0') {
        setRoleMenus(res.data);
        setCheckedKeys(res.data.map(item => {
          return item.menuId
        }))
      }
    })
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '最大长度为32'
          },
        ],
      },
    },
    {
      title: '角色编码',
      dataIndex: 'roleCode',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '最大长度为32'
          },
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input maxLength={33} {...fieldProps}/>;
      }
    },
    {
      title: '菜单功能权限',
      dataIndex: 'menuIds',
      hideInTable: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Tree
          checkable
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          onCheck={onCheck}
          checkedKeys={checkedKeys}
          onSelect={onSelect}
          selectedKeys={selectedKeys}
          treeData={menuTree}
        />;
      }
    },
    {
      title: '创建人',
      dataIndex: 'createByName',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <RangePicker showTime/>;
      }
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => setRow(record)}>
          详情
        </a>,
        <Divider type="vertical"/>,
        <a onClick={() => handleUpdateModalVisible(record)}>修改</a>,
        <Divider type="vertical"/>,
        <a onClick={() => deleteConfig(record)}>删除</a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="roleId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleCreateModalVisible()}>
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={async (params, sorter, filter) => {
          const param = {...params, pageNum: params.current};
          const res = await queryRole(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        // }}
      />
      <RoleForm title={formTitle} onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable
          onSubmit={async (value) => {
            const success = formTitle === '新增角色' ? await handleAdd(value) : await handleUpdate(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{
            form: formRef,
            layout: 'horizontal',
            labelAlign: 'left'
          }}
          rowKey="key"
          type="form"
          columns={columns}
        />
      </RoleForm>

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.roleName && (
          <ProDescriptions
            column={2}
            title={row?.roleName}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.roleName,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
